package com.shaoyu.tools.event.core;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;


/**
 * @author shaoyu
 * @date 2022/11/22 09:07
 */
public class FilterEventBus extends EventBus {

    private final InterceptorRegister interceptorRegister;

    private AtomicBoolean isRunning = new AtomicBoolean(false);

    private AtomicBoolean isShutDown = new AtomicBoolean(false);

    private Logger logger = LoggerFactory.getLogger(FilterEventBus.class);

    public FilterEventBus(ExecutorService executor, SubscriberExceptionHandler subscriberExceptionHandler) {
        super(subscriberExceptionHandler);
        interceptorRegister = new InterceptorRegister(executor);
    }

    @Override
    public void register(Object object) {
        this.registerInterceptor(object);
        super.register(object);
    }

    private void registerInterceptor(Object listener) {
        this.interceptorRegister.registerInterceptor(listener);
    }


    @Override
    public void unregister(Object listener) {
        this.interceptorRegister.unregisterInterceptor(listener);
        super.unregister(listener);
    }

    @Override
    public void post(Object event) {
        if(isShutDown.get()){
            logger.error("FilterEventBus is ShutDown! ");
            return;
        }
        isRunning.set(true);
        if (this.interceptorRegister.intercepted(event)) {
            return;
        }
        super.post(event);
        isRunning.set(false);
    }


    @PreDestroy
    public void shutdown(){
        int count = 0;
        //如果有任务执行 给10秒钟缓冲
        while (isRunning.get() && count < 1000){
            LockSupport.parkNanos(10*1000*1000L);
            count++;
        }
        isShutDown.set(true);
    }
}
